package fr.univ.lr.icone.gui;

import java.awt.Font;

import javax.swing.JPanel;

import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.StatisticalBarRenderer;
import org.jfree.data.statistics.DefaultStatisticalCategoryDataset;

public class AgentPopulationChartPanel extends JPanel {

	private static final long serialVersionUID = 1L;

	private DefaultStatisticalCategoryDataset dataset;

	private CategoryAxis xAxis;
	private ValueAxis yAxis;

	private CategoryItemRenderer renderer;
	private CategoryPlot plot;
	private JFreeChart chart;
	private ChartPanel chartPanel;

	public AgentPopulationChartPanel() {

		dataset = new DefaultStatisticalCategoryDataset();
		createDataset();

		/* Axis */
		xAxis = new CategoryAxis("Opinion");
		xAxis.setLowerMargin(0.01d);
		xAxis.setUpperMargin(0.01d);
		xAxis.setCategoryMargin(0.25d);
		yAxis = new NumberAxis("Number");

		renderer = new StatisticalBarRenderer();
		plot = new CategoryPlot(dataset, xAxis, yAxis, renderer);

		chart = new JFreeChart("Number(opinion)", new Font("Helvetica",
				Font.BOLD, 14), plot, true);

		chartPanel = new ChartPanel(chart);
		chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));

		add(chartPanel);
	}

	public void createDataset(int... values) {
		if (values.length != 10) {
			return;
		}
		dataset.clear();
		dataset.add(values[0], 0, "Number", "0");
		dataset.add(values[1], 0, "Number", "1");
		dataset.add(values[2], 0, "Number", "2");
		dataset.add(values[3], 0, "Number", "3");
		dataset.add(values[4], 0, "Number", "4");
		dataset.add(values[5], 0, "Number", "5");
		dataset.add(values[6], 0, "Number", "6");
		dataset.add(values[7], 0, "Number", "7");
		dataset.add(values[8], 0, "Number", "8");
		dataset.add(values[9], 0, "Number", "9");
	}

	public void refresh(int... values) {
		createDataset(values);
		plot.setDataset(dataset);
		this.repaint();
	}
}
